﻿namespace PNunitLauncherStarter
{
    using System;
    using System.Diagnostics;
    using System.Windows.Forms;
    using PNunitToolsClass;
    using System.IO;

    public partial class Form1 : Form
    {
        private LauncherConfig config;
        string path;

        public Form1()
        {
            InitializeComponent();
        }

        private void button_agent_load_Click(object sender, EventArgs e)
        {
            string d = Environment.CurrentDirectory;
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "conf files (*.conf)|*.conf";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    this.config = LauncherConfig.Load(openFileDialog.FileName);
                    MessageBox.Show("Load succeed!");
                    button_start.Enabled = true;
                    path = openFileDialog.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("Load failed! {0}", ex.Message));
                    button_start.Enabled = false;
                    path = null;
                }
            }
            Environment.CurrentDirectory = d;
        }

        private void button_start_Click(object sender, EventArgs e)
        {
            Process p = new Process();
            p.StartInfo.FileName = "pnunit-launcher.exe";
            p.StartInfo.Arguments = string.Format("{0}", this.path);
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = false;
            p.Start();
            p.WaitForExit();
            string result = string.Empty;
            if (string.IsNullOrEmpty(config.Config.ResultFileName))
            {
                result = p.StandardOutput.ReadToEnd();
            }
            p.Close();

            if (File.Exists("PNUnit_Report.xml"))
            {
                FileStream fs = new FileStream("PNUnit_Report.xml", FileMode.Open);
                StreamReader str = new StreamReader(fs);
                result = result + str.ReadToEnd();
                str.Close();
                fs.Close();
            }
            else  if (!string.IsNullOrEmpty(config.Config.ResultFileName))
            {

                FileStream fs = new FileStream(config.Config.ResultFileName, FileMode.Open);
                StreamReader str = new StreamReader(fs);
                result = str.ReadToEnd();
                str.Close();
                fs.Close();
            }
            OutPut o = new OutPut(result);
            o.Show();
        }
    }
}

